// Fill in your client ID and client secret that you obtained
// while registering the application
const clientID = 'f0d59e73bc4f39054bf4ef63f6a2f083dbdc8e068dbc4e65de61fd681e5d7a0f'
const clientSecret = '6cf4b6cf913146a3e2daa6e8f1f9fd621fad8bdc9ed630615c8495617ee027f6'
const grantType = 'authorization_code'
const redirectUri = 'http://localhost:8080/oauth/redirect'

const Koa = require('koa');
const path = require('path');
const serve = require('koa-static');
const route = require('koa-route');
const axios = require('axios');

const app = new Koa();

const main = serve(path.join(__dirname + '/public'));

const oauth = async ctx => {
  const requestToken = ctx.request.query.code;
  console.log('authorization code:', requestToken);

  const tokenResponse = await axios({
    method: 'post',
    url: 'https://gitee.com/oauth/token?' +
      `grant_type=${grantType}&` +
      `code=${requestToken}&` +
      `client_id=${clientID}&` +
      `redirect_uri=${redirectUri}&` +
      `client_secret=${clientSecret}`,
    headers: {
      accept: 'application/json'
    }
  });

  const accessToken = tokenResponse.data.access_token;
  console.log(`access token: ${accessToken}`);

  const result = await axios({
    method: 'get',
    url: `https://gitee.com/api/v5/user`,
    headers: {
      accept: 'application/json',
      Authorization: `token ${accessToken}`
    }
  });
  console.log(result.data);
  const name = result.data.name;

  ctx.response.redirect(`/welcome.html?name=${name}`);
};

app.use(main);
app.use(route.get('/oauth/redirect', oauth));

app.listen(8080);
